var childProcess = require('child_process');
var util = require('util');
var errors = require('../error/errors');

exports.composeArgsStrFromArr = function (argsArr) {
    var finalCommand = '';
    if (argsArr) {
        for (var oneArgIdx in argsArr) {
            finalCommand += ' ' + argsArr[oneArgIdx];
        }
    }
    return finalCommand;
}
exports.executeShellCommand = function (command, args, callback, endCallback) {
    var getExecutiveCommandStr = function () {
        var finalCommand = command;
        finalCommand += exports.composeArgsStrFromArr(args);
        return finalCommand;
    }
    util.log('[LOADED SHELL COMMAND]: [ ' + getExecutiveCommandStr() + ' ] ++');
    var oneExec = childProcess.exec(
        getExecutiveCommandStr(),
        function (err, stdout, stderr) {
            util.log('++ [EXECUTING SHELL COMMAND]: [ ' + getExecutiveCommandStr() + ' ] ++');
            util.log('stdout: ' + stdout);
            util.error('stderr: ' + stderr);
            if (err !== null) {
                util.log('== [STDERR] ' + err + ' ==');
                callback(new errors.getErrorInstance(
                    errors.errorsName.invocation,
                    err
                ));
            } else {
                callback(stdout);
                util.log('-- [COMPLETED MESSAGE START] --');
                util.log(stdout);
                util.log('-- [COMPLETED MESSAGE END] --');
            }
        }
    );
    oneExec.on('data', function (data) {
        console.log(data);
    });
    oneExec.on('close', function (code) {
        util.log('-- [FINISHED] COMMAND [' + getExecutiveCommandStr() + '] EXIT WITH CODE ' + code + ' --');
        if(endCallback !== undefined){
            endCallback(code);
        }
    });
}
